﻿using Grow.Domain.DomainRepository;
using Grow.EventBus.Cap.SubscriberDomainEvents;
using Grow.Module.Service;
using Grow.Scheduler.Job;

namespace Grow.EventBus.Cap.Jobs
{
    public class ExpirerPublisherDomainEventJob : JobBase
    {
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        private readonly ISubscriberDomainEventRepository _publisherDomainEventRepository;
        public ExpirerPublisherDomainEventJob(IServiceContext serviceContext) : base(serviceContext)
        {
            _unitOfWorkManager = serviceContext.GetRequiredService<IUnitOfWorkManager>();
            _publisherDomainEventRepository = serviceContext.GetRequiredService<ISubscriberDomainEventRepository>();
        }

        public override async Task ExecuteAsync(CancellationToken cancellationToken)
        {
            var now = DateTimeOffset.Now;
            var unitOfWork = _unitOfWorkManager.GetUnitOfWork();

            var publisherDomainEvents = await _publisherDomainEventRepository.ToListAsync(a =>
                a.ExpireTime < now && a.ExpireTime != null
                && a.EventStatus == SubscriberDomainEventStatus.Success
               ,cancellationToken);

            foreach (var publisherDomainEvent in publisherDomainEvents)
            {
                await _publisherDomainEventRepository.RemoveAsync(publisherDomainEvent, cancellationToken);
            }
            await unitOfWork.CommitAsync(cancellationToken);
        }
    }
}
